<template>
    <YvRow :span="40" align=center>
        <YvCol :span="29" id="mainView" @contextmenu.prevent.stop="mainViewRClick">
            <YvCol v-if="loading.per != 100">
                <YvCol :span=40 id="MainViewCopyright">
                    <span v-for="index of 16" :key="index" :class="index % 4 != 0 ? 'hasRight' : ''">
                        Element {{ index }} In Loading ... <br>Powered By reYour
                    </span>
                </YvCol>
                <div>
                    主视图加载中 {{ loading.per }}%
                    <br />
                    运行 {{ loading.text }}
                    <span v-html="loading.change"></span>
                </div>
            </YvCol>
            <div v-else id="mainViewParsed" v-html="articleHTML" v-on:click.native="editItem($event.target)">
            </div>
        </YvCol>
        <YvRow :span="9" id="editorView">
            <YvRow class="editorTitle">
                <YvCol :span="20">
                    当前选中: {{ activeEditObj ? activeEditObj.id : '主视图' }}
                </YvCol>
                <YvCol :span="20">
                    <input @change="loadFile" type="file" accept=".rao" ref="raofile" style="display: none;" />
                    <YvBtn @click="saveFile">保存</YvBtn>
                    <YvBtn @click="uploadRAO">上传</YvBtn>
                </YvCol>
            </YvRow>
            <YvRow :span="40" id="yv-article-editor-choose">
                <YvCol :span="10" @click="editorMenuChange('val')">
                    控件属性
                </YvCol>
                <YvCol :span="10" @click="editorMenuChange('pos')">
                    控件定位
                </YvCol>
                <YvCol :span="10" @click="editorMenuChange('event')">
                    控件事件
                </YvCol>
            </YvRow>
            <YvRow :span="40" v-if="!activeEditObj">
                未选中
            </YvRow>
            <YvRow :span="40" v-else class="editorInputView">
                <YvCol :span="40" v-for="item in Object.values(activeEditObj.attr)" v-show='item.constructor === Object'
                    class="editorInput">
                    <YvInput :label="item.info" v-model="item.value" :placeholder="item.default + ' [默认值]'"
                        @blur="inputBlur"></YvInput>
                </YvCol>

            </YvRow>
        </YvRow>
    </YvRow>
    <!-- 右键菜单 -->
    <YvRow :span="4">
        <YvGroup text="右键菜单" class="yv-group-block">
            <YvGroupItem v-for="item in rightClickMenu" @click.stop="item.click">{{ item.text }}</YvGroupItem>
        </YvGroup>
    </YvRow>
</template>

<script>
import { saveAs } from 'file-saver';
function sleep(ms) {
    return new Promise(function (resolve) {
        setTimeout(resolve, ms);
    })
}
export default {
    data() {
        return {
            mainData: {

            },
            // 1. ATTR 2.POSITION 3.FUNCTION
            editType: 1,
            // 已经选择的可编辑的Object
            activeEditObj: null,
            loading: {
                text: 'InLoading()',
                per: 0,
                change: '.',
            },
            articleArr: [
                {
                    // 组件ID
                    id: "LABEL1",
                    // 组件类型
                    type: "LABEL",
                    // 类
                    classes: ["YV-PARSE-LABEL-DEFAULT"],
                    // 定位
                    position: {
                        type: "absolute",
                        x: 0,
                        y: 0,
                        group: false,
                    },
                    // 组件属性
                    attr: {
                        text: {
                            type: 'EDIT-PARSE',
                            info: "文字",
                            value: null,
                            default: 'LABEL1',
                            required: true,
                            parse: {
                                // 解析类型为文字
                                type: "text",
                            }
                        },
                        color: {
                            type: 'EDIT-PARSE',
                            // 属性
                            info: "颜色",
                            // 属性值
                            value: null,
                            // 默认值
                            default: "var(--yv-main-color)",
                            //是否必填
                            required: true,
                            // 解析属性
                            parse: {
                                // 类型为内部CSS
                                type: "inner-css",
                                // 内部CSS,
                                css: {
                                    key: 'color',
                                    value: '[COLOR]'
                                }
                            }
                        },
                        fontSize: {
                            type: 'EDIT-PARSE',
                            // 属性
                            info: "字体大小",
                            // 属性值
                            value: null,
                            // 默认值
                            default: "12px",
                            //是否必填
                            required: true,
                            // 解析属性
                            parse: {
                                // 类型为内部CSS
                                type: "inner-css",
                                // 内部CSS,
                                css: {
                                    key: 'font-size',
                                    value: '[FONTSIZE]'
                                }
                            }
                        },
                    },

                    // 
                },
                {
                    // 组件ID
                    id: "LABEL2",
                    // 组件类型
                    type: "LABEL",
                    // 类
                    classes: ["YV-PARSE-LABEL-DEFAULT"],
                    // 定位
                    position: {
                        type: "absolute",
                        x: 30,
                        y: 0,
                        group: false,
                    },
                    // 组件属性
                    attr: {
                        text: {
                            type: 'EDIT-PARSE',
                            info: "文字",
                            value: null,
                            default: 'LABEL2',
                            required: true,
                            parse: {
                                // 解析类型为文字
                                type: "text",
                            }
                        },
                        color: {
                            type: 'EDIT-PARSE',
                            // 属性
                            info: "颜色",
                            // 属性值
                            value: null,
                            // 默认值
                            default: "var(--yv-main-color)",
                            //是否必填
                            required: true,
                            // 解析属性
                            parse: {
                                // 类型为内部CSS
                                type: "inner-css",
                                // 内部CSS,
                                css: {
                                    key: 'color',
                                    value: '[COLOR]'
                                }
                            }
                        },
                        fontSize: {
                            type: 'EDIT-PARSE',
                            // 属性
                            info: "字体大小",
                            // 属性值
                            value: null,
                            // 默认值
                            default: "12px",
                            //是否必填
                            required: true,
                            // 解析属性
                            parse: {
                                // 解析类型为内部CSS
                                type: "inner-css",
                                // 内部CSS,
                                css: {
                                    key: 'font-size',
                                    value: '[FONTSIZE]'
                                }
                            }
                        },
                    },
                    // 
                }
            ]
        }
    },
    computed: {
        rightClickMenu() {
            return [
                {
                    text: "",
                    click: () => {
                        this.testMethods();
                    }
                }
            ]
        }
    },
    async created() {
        this.loadingChange();
        await this.inLoad();
    },
    methods: {
        testMethods() {
            console.log("成功！ =》 testMethods()")
        },
        // 失去焦点的事件
        async inputBlur() {
            await this.inLoad(this.articleArr)
        },
        mainViewRClick() {

        },
        // 显示 ...
        async loadingChange() {
            var count = 0;
            while (this.loading.per != 100) {
                count++;
                this.loading.change += '.';
                if (count % 5 == 0) {
                    this.loading.change = '.';
                }
                await sleep(1000);
            }
        },
        // 解除选中
        reIndent(dom){
            var oldDocument = Array.from(document.getElementsByClassName('YV-INEDIT'));
            for (var i = 0; i < oldDocument.length; i++) {
                oldDocument[i].classList.remove('YV-INEDIT');
                if (dom == true || (dom != undefined && oldDocument[i] == dom)) {
                    this.activeEditObj = null
                    return false
                }
            }
            return true
        },
        // 加载
        async inLoad() {
            this.loading.per = 5
            this.loading.text = 'parseArray()'
            await this.parseArray(this.articleArr);
            this.loading.per = 50
            this.loading.text = 'mountFunc()'
            await this.mountFunc();
            this.loading.per = 100
        },
        //点击编辑
        editItem(dom) {
            //DOM
            // STEP 1 删除之前已经存在的INEDIT DOM中的class
            if(!this.reIndent(dom)){
                return
            }
            if (this.activeEditObj) {
                var oldClassesIndex = this.activeEditObj.classes.indexOf('YV-INEDIT');
                this.activeEditObj.classes = this.activeEditObj.classes.slice(oldClassesIndex, 1)
            }
            // alert(dom);
            // STEP 2 添加INEDIT类
            dom.classList.add('YV-INEDIT');
            // alert(dom);
            // STEP 3 获取已选择的Object
            var objId = dom.getAttribute('id');
            var activeObj = this.articleArr.find(e => e.id === objId);
            console.log(activeObj.classes);
            activeObj.classes.push('YV-INEDIT');
            this.activeEditObj = activeObj;
        },
        // 装载HTML
        async mountFunc() {

        },
        //#region 解析属性  
        async parseArray(articleArray) {
            this.articleHTML = '';
            for (var i = 0; i < articleArray.length; i++) {
                await this.parse(articleArray[i]);
            }
        },
        async parse(articleObj) {
            var type = articleObj.type
            // console.log(type);
            switch (type) {
                // TODO 8 / 10
                case 'LABEL':
                    await this.parseLABEL(articleObj);
                    break;
                // TODO 0 /10
                case 'INPUT':
                    this.parseINPUT(articleObj);
                    break;
                // TODO 0 / 10
                case 'BUTTON':
                    this.parseBUTTON(articleObj);
                    break;
                // TODO 0 / 10
                case 'GROUP':
                    this.parseGROUP(articleObj);
                    break;
            }

        },
        async parseLABEL(articleObj) {
            var labelHtml = "";
            var labelId = `YV-PARSED-LABEL-${articleObj.id}`;
            labelHtml = `<span id='${articleObj.id}' class='clickable YV-CLICK-EDIT YV-PARSED-LABEL ${articleObj.classes.join(' ')}' style='[$POSITION$][COLOR][FONTSIZE]'>${articleObj.attr.text.value || articleObj.attr.text.default}</span>`;
            // 解析位置信息 
            var posObj = articleObj.position;
            var position = `position: ${posObj.type};top: ${posObj.y};left: ${posObj.x};`
            labelHtml = labelHtml.replace('[$POSITION$]', position);
            // 解析CSS
            var parseValues = Object.values(articleObj.attr);
            for (var i = 0; i < parseValues.length; i++) {
                const element = parseValues[i];
                if (element.constructor !== Object || element.parse.type != 'inner-css') {
                    continue;
                }
                let styleValue = element.value || element.default;
                labelHtml = labelHtml.replace(element.parse.css.value, `${element.parse.css.key}: ${styleValue};`)
                // labelStyle= labelStyle.replace(element.parse.css.value, `${element.parse.css.key}: ${styleValue};`)
            }
            this.articleHTML += labelHtml;
            return this.articleHTML;
        },
        //#endregion
        uploadRAO(){
            this.$refs.raofile.click()
        },
        async loadFile(e) {
            let rao = e.target.files[0]
            let that = this
            let fr = new FileReader()
            fr.onload = (e) => {
                that.readRAOFile(e.target.result , that)
            };
            fr.readAsText(rao)
        },
        async readRAOFile(rao,that){
            rao = rao.split('\n')
            let raoValue
            rao.forEach(element => {
                if(element.split('@')[1].includes('Value')){
                    raoValue = JSON.parse(element.split('@')[2]);
                }
            });             
            Object.assign(this.data,raoValue)
            await this.inLoad();
            this.reIndent(true)
        },
        async saveFile() {
            let fileContent = `@Intro: @This File type is {Reyour Article Object}. Open https://ry.wiki/article/editor\n`;
            fileContent += '@Encrypt: @None\n'
            fileContent += '@Decrypt: @None\n'
            fileContent += '@Private: @None\n'
            fileContent += '@Author: @若雨\n'
            fileContent += `@LTime: @${new Date().toDateString()}\n`
            let savedJson = {
                mainData: this.mainData,
                articleArr: this.articleArr
            }
            fileContent += '@Value: @' + JSON.stringify(savedJson)
            console.log(fileContent)
            const fileName = 'Reyour Article Object.rao';
            const fileType = 'text/plain;charset=utf-8';
            const blob = new Blob([fileContent], { type: fileType });
            saveAs(blob, fileName);
        }
    },
}
</script>

<style style="scoped">
#yv-article-editor-choose {
    flex-wrap: nowrap;
    overflow-x: scroll;
    border-top: 1px dotted var(--yv-main-color);
    padding: 4pt 0;
    justify-content: space-around;
    margin: 4pt auto;
}

#yv-article-editor-choose .yv-col:hover{
    cursor: pointer;
}

#yv-article-editor-choose::-webkit-scrollbar {
    background: black;
    height: 8pt;
}

#mainView {
    width: 100%;
    height: 720px;
    margin: 1% 0;
    outline: 1px solid black;
    border-radius: 1pt;
    overflow: scroll;
    position: relative;
    background: white;
    z-index: 2;
}

#MainViewCopyright {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    display: block;
    z-index: -1;
}

#MainViewCopyright span {
    width: 24.8%;
    height: 25%;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    color: rgba(0, 0, 0, .11);
    z-index: -1;

}

#MainViewCopyright .hasRight {
    border-right: 1px dashed rgba(0, 0, 0, .05);
}

#MainViewCopyright span {
    border-top: 1px dashed rgba(0, 0, 0, .05);
}

#editorView {
    display: block;
    /* padding: 2px; */
    border-radius: 10px 0 0 10px;
    margin: 1% 0;
    height: 720px;
    border: 1px solid var(--yv-main-color);
    overflow-y: scroll;
    position: relative;
}

#editorView .yv-input-label {
    font-size: 10pt;
}

.YV-INEDIT {
    outline: 1px dashed blue;
    outline-offset: 2px;
}

#mainViewParsed * {
    cursor: pointer;
}

.editorInput {
    margin: 6pt 0;
}
</style>